"""
Demo script showing the new Markdown table feature in reports.
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from attribution_agent import AttributionAgent
from examples.sample_data import generate_ecommerce_data


def demo_table_report():
    """Demo: Attribution report with Markdown tables."""
    print("=" * 80)
    print("DEMO: Attribution Report with Markdown Tables")
    print("=" * 80)

    # Generate sample data
    print("\n1. Generating sample data...")
    data = generate_ecommerce_data(start_date="2025-09-01", days=60)
    print(f"   Generated {len(data)} rows")

    # Initialize agent
    print("\n2. Initializing Attribution Agent...")
    agent = AttributionAgent(config={
        'llm_model': 'openai/gpt-4o',
        'max_drill_depth': 2,
        'enable_llm_reasoning': True  # Set to False to see simple report with tables
    })

    # Run analysis
    print("\n3. Running analysis...")
    query = """
    分析最近两周的收入表现，与前两周比较。
    找出导致变化的主要原因。
    """

    result = agent.analyze(query=query, data=data)

    # Display report
    print("\n4. Generated Report with Markdown Tables:")
    print("=" * 80)
    report = agent.get_report(result)
    print(report)
    print("=" * 80)

    # Save report to file
    output_file = "attribution_report.md"
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(report)
    print(f"\n✓ Report saved to: {output_file}")

    return result


if __name__ == "__main__":
    print("Attribution Report Table Demo\n")

    # Check API key
    has_api_key = os.getenv('OPENROUTER_API_KEY') or os.getenv('OPENAI_API_KEY')

    if not has_api_key:
        print("⚠️  No API key found - using simple report mode")
        print("   To enable LLM-powered reports, set OPENROUTER_API_KEY or OPENAI_API_KEY\n")

    try:
        demo_table_report()

        print("\n🎉 Demo completed successfully!")
        print("\nThe report includes:")
        print("  • Markdown tables for data visualization")
        print("  • Anomaly detection summary")
        print("  • Drill-down analysis with metrics")
        print("  • Metric decomposition")
        print("  • Root cause analysis")

    except Exception as e:
        print(f"\n❌ Error: {str(e)}")
        import traceback
        traceback.print_exc()
